//
//  KLHistoricalRateController.m
//  KLCurrency
//
//  Created by apple on 2017/12/4.
//  Copyright © 2017年 bonc. All rights reserved.
//

#import "KLHistoricalRateController.h"

#import "KLHistoricalRateCurrencyView.h"
#import "KLTopTabBar.h"
#import "KLHistoricalRateChartView.h"

#import "KLHistoricalRate.h"

#import "KLNetWorkService.h"
#import "KLNetWorkHelper.h"

#import "KLCurrencyService.h"

#import "KLDateTool.h"

typedef NS_ENUM(NSInteger,KLTimeRange){
    KLTimeRangeWeek = 0,
    KLTimeRangeMonth,
    KLTimeRangeSixMonths,
    KLTimeRangeYear,
    KLTimeRangeThreeYears,
};

static const CGFloat currencyViewHeight = 150.0f;
static const CGFloat periodTabViewHeight = 50.0f;

@interface KLHistoricalRateController ()<KLTopTabBarDelegate,KLHistoricalRateCurrencyViewDelegate>
@property (copy, nonatomic) NSString *localCurrency;
@property (strong, nonatomic) KLHistoricalRateCurrencyView *currencyView;
@property (strong, nonatomic) KLHistoricalRateChartView *chartView;
@property (strong, nonatomic) KLTopTabBar *periodTabView;
@property (assign, nonatomic) NSTimeInterval currentTimeInterval;
@property (assign, nonatomic) BOOL isLocal;
@property (assign, nonatomic) BOOL canExchangeCurrencies;

@end

@implementation KLHistoricalRateController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.localCurrency = [KLCurrencyService getLocalCurrencyAbbr];
    
    [self initNavigationItem];
    [self initExchangeRateUI];
    
    //第一次加载数据
    [self loadDataFirstTime];
}

- (void)initExchangeRateUI {
    //汇率货币选择栏
    KLHistoricalRateCurrencyView *currencyView = [KLHistoricalRateCurrencyView historicalRateCurrencyView];
    currencyView.frame = CGRectMake(0, kNavigationBarHeight+kStatusBarHeight, kScreenWidth, currencyViewHeight);
    currencyView.exchangeCurrency = self.exchangeCurrency;
    currencyView.localCurrency = self.localCurrency;
    
    currencyView.delegate = self;
    [self.view addSubview:currencyView];
    self.currencyView = currencyView;
    //增加侧滑返回手势
    UIScreenEdgePanGestureRecognizer *edgePan = [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self action:@selector(popBack)];
    edgePan.edges = UIRectEdgeLeft;
    [currencyView addGestureRecognizer:edgePan];
    
    //汇率时间段选择栏
    NSArray * titles = @[@"7天",@"1月",@"6月",@"1年",@"3年"];
    CGRect tabbarFrame = CGRectMake(0, CGRectGetMaxY(currencyView.frame), kScreenWidth, periodTabViewHeight);
    KLTopTabBar *tabbar = [[KLTopTabBar alloc] initWithFrame:tabbarFrame titles:titles];
    tabbar.delegate = self;
    tabbar.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:tabbar];
    self.periodTabView = tabbar;
    
    //汇率曲线及统计视图
    CGFloat chartViewMinY = CGRectGetMaxY(tabbar.frame);
    KLHistoricalRateChartView *chartView = [[KLHistoricalRateChartView alloc] initWithFrame:CGRectMake(0, chartViewMinY, kScreenWidth, kScreenHeight-chartViewMinY)];
    [self.view addSubview:chartView];
    self.chartView = chartView;
}

- (void)loadDataFirstTime {
    [self.periodTabView selectDefaultTabItem:0];
}

- (void)initNavigationItem {
    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStylePlain target:self action:@selector(popBack)];
    [leftItem setTintColor:UIColorFromRGB(0X99A4BF)];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"汇率详情";
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSFontAttributeName:[UIFont systemFontOfSize:18.0],
       NSForegroundColorAttributeName:[UIColor blackColor]}];
}
- (void)popBack {
    if (self.delegate && [self.delegate respondsToSelector:@selector(popHistoricalRateController)]) {
        [self.delegate popHistoricalRateController];
    }
    //直接返回不作处理要把changing清空
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)selectTabItemAtIndex:(NSUInteger)index {
    //切换前先清空之前数据
    [self.chartView clearCurveView];
    
    if (NEED_HISTORICALRATETEST) {
        KLLog(@"仿真（本地数据）测试");
        self.chartView.state = KLHistoricalRateStateLocalTest;
        switch (index) {
            case KLTimeRangeWeek:{
                NSArray *dateArr = [KLDateTool recentWeekPeriodDates];
                KLLog(@"周");
                [self testUpdateChartViewWithRecentPeriodDates:dateArr];
            }
                break;
            case KLTimeRangeMonth:{
                NSArray *dateArr = [KLDateTool recentMonthPeriodDates];
                KLLog(@"月");
                [self testUpdateChartViewWithRecentPeriodDates:dateArr];
            }
                break;
            case KLTimeRangeSixMonths:{
                NSArray *dateArr = [KLDateTool recentSixMonthsPeriodDates];
                KLLog(@"6月");
                [self testUpdateChartViewWithRecentPeriodDates:dateArr];
            }
                break;
            case KLTimeRangeYear:{
                NSArray *dateArr = [KLDateTool recentYearPeriodDates];
                KLLog(@"年");
                [self testUpdateChartViewWithRecentPeriodDates:dateArr];
            }
                break;
            case KLTimeRangeThreeYears:{
                KLLog(@"3年");
                //暂时没有三年以上本地数据
                self.chartView.state = KLHistoricalRateStateRequestFailed;
            }
                break;
            default:
                break;
        }
    } else {
        if ([KLNetWorkHelper isExistNetWork]) {
            KLLog(@"可以连接互联网");
            [self.chartView startLoading];
            [self addCover];
            switch (index) {
                case KLTimeRangeWeek:{
                    NSArray *dateArr = [KLDateTool recentWeekPeriodGapDates];
                    KLLog(@"周");
                    [self updateChartViewWithRecentPeriodDates:dateArr];
                }
                    break;
                case KLTimeRangeMonth:{
                    NSArray *dateArr = [KLDateTool recentMonthPeriodGapDates];
                    KLLog(@"月");
                    [self updateChartViewWithRecentPeriodDates:dateArr];
                }
                    break;
                case KLTimeRangeSixMonths:{
                    NSArray *dateArr = [KLDateTool recentSixMonthsPeriodGapDates];
                    KLLog(@"6月");
                    [self updateChartViewWithRecentPeriodDates:dateArr];
                }
                    break;
                case KLTimeRangeYear:{
                    NSArray *dateArr = [KLDateTool recentYearPeriodGapDates];
                    KLLog(@"年");
                    [self updateChartViewWithRecentPeriodDates:dateArr];
                }
                    break;
                case KLTimeRangeThreeYears:{
                    NSArray *dateArr = [KLDateTool recentThreeYearsPeriodGapDates];
                    KLLog(@"3年");
                    [self updateChartViewWithRecentPeriodDates:dateArr];
                }
                    break;
                default:
                    break;
            }
        } else {
            KLLog(@"不可以连接互联网");
            self.chartView.state = KLHistoricalRateStateNoNetWork;
            [self.chartView stopLoading];
            [self removeCover];
        }
    }
}

- (void)updateChartViewWithRecentPeriodDates:(NSArray<NSString *> *)dates {
    //请求网络数据
    [KLNetWorkService getCurrencyLayerHistoricalRatesWithExchangeCurrency:self.exchangeCurrency localCurrency:self.localCurrency datePeriod:dates success:^(NSArray<KLHistoricalRate *> *entities) {
        
        self.chartView.dataArray = entities;
        self.chartView.state = KLHistoricalRateStateRequestSuccess;
        [self.chartView stopLoading];
        [self removeCover];
        
    } failure:^(NSString *error) {
        
        self.chartView.state = KLHistoricalRateStateRequestFailed;
        [self.chartView stopLoading];
        [self removeCover];
        
    }];
}

- (void)testUpdateChartViewWithRecentPeriodDates:(NSArray<NSString *> *)dates {
    //请求本地随机数据
    
    [KLNetWorkService testCurrencyLayerHistoricalRatesWithExchangeCurrency:self.exchangeCurrency localCurrency:self.localCurrency datePeriod:dates success:^(NSArray<KLHistoricalRate *> *entities){
        
        self.chartView.dataArray = entities;
        self.chartView.state = KLHistoricalRateStateLocalTest;
        
    } failure:^(NSString *error) {
        self.chartView.state = KLHistoricalRateStateRequestFailed;
        [self.chartView stopLoading];
        [self removeCover];
    }];
}

#pragma mark - header view delegate
- (void)exchangeCurrencies {
    [_chartView reverseCurrencies];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
